import { useState, useEffect, useCallback } from "react";
import { Step, StepConfig } from '../types';

const defaultSteps: Step[] = [
  {
    element: ".step-1",
    popover: {
      title: "欢迎使用",
      description: "这是第一步引导",
      side: "bottom",
      align: "start",
    },
    customStyles:
      ".driver-popover { \n  max-width: 100vw !important; \n}\n.driver-popover-description { \n  font-size: 12px !important; \n  word-break: keep-all !important; \n}",
  },
  {
    element: ".step-2",
    popover: {
      title: "功能介绍",
      description: "这是第二步引导",
      side: "top",
      align: "center",
    },
  },
];

export const useStepConfigs = () => {
  const [configs, setConfigs] = useState<StepConfig[]>([]);
  const [currentConfigId, setCurrentConfigId] = useState<string>("default");
  const [steps, setSteps] = useState<Step[]>([]);

  // 初始化加载配置
  const loadConfigs = useCallback(async () => {
    try {
      const result = await chrome.storage.local.get([
        "stepConfigs",
        "currentConfigId",
      ]);

      let loadedConfigs: StepConfig[] = [];
      if (result.stepConfigs && Array.isArray(result.stepConfigs)) {
        loadedConfigs = result.stepConfigs;
      } else {
        const defaultConfig: StepConfig = {
          id: "default",
          name: "默认配置",
          steps: defaultSteps,
          createdAt: Date.now(),
          updatedAt: Date.now(),
        };
        loadedConfigs = [defaultConfig];
        await chrome.storage.local.set({ stepConfigs: loadedConfigs });
      }
      setConfigs(loadedConfigs);

      const configId = result.currentConfigId || "default";
      setCurrentConfigId(configId);

      const currentConfig = loadedConfigs.find(
        (config) => config.id === configId
      );
      if (currentConfig) {
        setSteps(currentConfig.steps);
      } else {
        setSteps(defaultSteps);
      }
    } catch (error) {
      console.error("加载配置失败:", error);
    }
  }, []);

  // 保存配置到存储
  const saveConfigs = useCallback(async (updatedConfigs: StepConfig[]) => {
    try {
      setConfigs(updatedConfigs);
      await chrome.storage.local.set({ stepConfigs: updatedConfigs });
    } catch (error) {
      console.error("保存配置失败:", error);
    }
  }, []);

  // 创建新配置
  const createNewConfig = useCallback(
    async (configName: string) => {
      if (!configName.trim()) return;

      const newConfig: StepConfig = {
        id: `config_${Date.now()}`,
        name: configName.trim(),
        steps: [
          {
            element: "",
            popover: {
              title: "新步骤",
              description: "请填写描述",
              side: "bottom",
              align: "start",
            },
          },
        ],
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };

      const updatedConfigs = [...configs, newConfig];
      await saveConfigs(updatedConfigs);

      setCurrentConfigId(newConfig.id);
      setSteps(newConfig.steps);
      await chrome.storage.local.set({ currentConfigId: newConfig.id });
    },
    [configs, saveConfigs]
  );

  // 切换配置
  const switchConfig = useCallback(
    async (configId: string) => {
      const config = configs.find((c) => c.id === configId);
      if (!config) return;

      setCurrentConfigId(configId);
      setSteps(config.steps);
      await chrome.storage.local.set({ currentConfigId: configId });
    },
    [configs]
  );

  // 删除配置
  const deleteConfig = useCallback(
    async (configId: string) => {
      if (configId === "default" || configs.length <= 1) return;

      const updatedConfigs = configs.filter((c) => c.id !== configId);
      await saveConfigs(updatedConfigs);

      if (currentConfigId === configId) {
        const firstConfig = updatedConfigs[0];
        setCurrentConfigId(firstConfig.id);
        setSteps(firstConfig.steps);
        await chrome.storage.local.set({ currentConfigId: firstConfig.id });
      }
    },
    [configs, currentConfigId, saveConfigs]
  );

  // 重命名配置
  const renameConfig = useCallback(
    async (configId: string, newName: string) => {
      if (!newName.trim()) return;

      const updatedConfigs = configs.map((config) => {
        if (config.id === configId) {
          return {
            ...config,
            name: newName.trim(),
            updatedAt: Date.now(),
          };
        }
        return config;
      });

      await saveConfigs(updatedConfigs);
    },
    [configs, saveConfigs]
  );

  // 自动保存步骤变化
  useEffect(() => {
    if (steps.length === 0) return;

    const timeoutId = setTimeout(async () => {
      try {
        const updatedConfigs = configs.map((config) => {
          if (config.id === currentConfigId) {
            return {
              ...config,
              steps: steps,
              updatedAt: Date.now(),
            };
          }
          return config;
        });

        await saveConfigs(updatedConfigs);
      } catch (error) {
        console.error("自动保存失败:", error);
      }
    }, 1000);

    return () => clearTimeout(timeoutId);
  }, [steps, currentConfigId, configs, saveConfigs]);

  return {
    configs,
    currentConfigId,
    steps,
    setSteps,
    loadConfigs,
    createNewConfig,
    switchConfig,
    deleteConfig,
    renameConfig,
  };
};
